#include "transferthread.h"

#include <QCoreApplication>



TransferThread::TransferThread(QObject *parent) :
    QThread(parent),
    m_serial(new QSerialPort),
    m_timer(new QTimer(this))
{
    m_serial->moveToThread(this);

    m_timer->moveToThread(this);

    m_ymodem = new ProtocolYModem(m_serial);

    connect(m_timer, &QTimer::timeout, this, [=]() {
        ymodemRun();
    });
}

TransferThread::~TransferThread()
{
    qDebug() << "TransferThread deleteLater";

    m_serial->close();

    delete m_ymodem;
    delete m_timer;

    delete m_serial;
}

void TransferThread::startTrans()
{
    if(!m_serial->open(QIODevice::ReadWrite)){
        qDebug() << __FILE__ << "Serial open failed";
        return;
    }

    m_ymodem->begin(dir, fileName);
    m_timer->start(1);

    if(!isRunning()){
        start();
    }
}

void TransferThread::stopTrans()
{
    m_timer->stop();
    m_serial->close();
}



void TransferThread::setDirection(Protocol::Direction _dir)
{
    dir = _dir;
}

void TransferThread::setFileName(const QString &name)
{
    fileName = name;
}

void TransferThread::setProtocol(ProtocolType pro)
{
    protocol_type = pro;
}

void TransferThread::setSerialInfo(const SettingsDialog::Settings &serialSet)
{
    m_serial->setPortName(serialSet.portName);
    m_serial->setPortName(serialSet.portName);
    m_serial->setBaudRate(serialSet.baudRate);
    m_serial->setDataBits(serialSet.dataBits);
    m_serial->setParity(serialSet.parity);
    m_serial->setStopBits(serialSet.stopBits);
    m_serial->setFlowControl(serialSet.flowControl);
}


void TransferThread::ymodemRun(void) {
    bool is_over = 0;
    m_ymodem->run(dir);

    emit displayProgress(m_ymodem->getProgress());

    if (m_ymodem->isOver()) {
        bool succesful = (m_ymodem->getStatus() == YModem::StatusFinish);
        emit transferOver(succesful ? "文件传输成功" : "文件传输失败", succesful);
    }

}
